package Veterinaria.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import Veterinaria.excepcion.CodigoDuplicadoExcepcion;
import Veterinaria.excepcion.DAOExcepcion;
import Veterinaria.modelo.Dueno;
import Veterinaria.modelo.Factura;
import Veterinaria.modelo.FacturaDetalleTMP;
import Veterinaria.modelo.Paciente;
import Veterinaria.negocio.GestionFactura;
import Veterinaria.negocio.GestionFacturaDetalle;
import Veterinaria.negocio.GestionPersona;

/**
 * Servlet implementation class FacturaServlet
 */
@WebServlet("/FacturaServlet")
public class FacturaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FacturaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        JSONArray arrayObj = new JSONArray();
        JSONObject obj1 = new JSONObject();
		GestionPersona dueno = new GestionPersona();
		String nom = null;
		
		try {
			String query = request.getParameter("term");
	        query = query.toLowerCase();
	        
			Collection<Dueno> duenos = dueno.ListaDuenoXNombre(query);

			for (Dueno due : duenos) {
				if (due.getApellido_persona().toLowerCase().startsWith(query))
					nom = due.getApellido_persona() + " " + due.getNombre_persona();
				obj1.put("label", nom);
				obj1.put("value", nom);
				obj1.put("id", due.getCodigo_persona());
				arrayObj.add(obj1.toString());
				obj1.clear();
			}

		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
	        out.println(arrayObj);
	        out.close();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		
		GestionFactura fac = new GestionFactura();

		String  idNomCliente = request.getParameter("idNomCliente");
		String  NomCliente = request.getParameter("NomCliente");
		String  idfactura = request.getParameter("idfactura");
		String  fechafactura = request.getParameter("fechafactura");
		String  total = request.getParameter("total");
		String  estado = "1";
		
		double xtotal = Double.parseDouble(total);

			try {
				fac.insertarfactura(idfactura, idNomCliente, fechafactura, xtotal, estado);
			} catch (DAOExcepcion e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CodigoDuplicadoExcepcion e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 
		
//		request.setAttribute("var1", idfactura);
//		request.setAttribute("var2", idNomCliente);
//		request.setAttribute("var3", NomCliente);
//		request.setAttribute("var4", fechafactura );
//		request.setAttribute("var5", total );	
		
	// Insertar en Detalle////////////////////////////////////////////	
			GestionFacturaDetalle fact = new GestionFacturaDetalle();
//			try {
//				request.setAttribute("facturas", fact.listartemporal());
//				
//			} catch (DAOExcepcion e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
	
			Collection<FacturaDetalleTMP> o =null;
			try {
				o = fact.listartemporal();

			} catch (DAOExcepcion e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	
			if(o!= null) { 
			int i = 1;
			for(FacturaDetalleTMP x : o) {

				try {
					fact.insertarfacturadetalle(x.getIdfactura(), i, x.getidArticulo(), x.getCantidad(), x.getTotal());
				} catch (DAOExcepcion e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	
			   	i++;
			}
			
			try {
				fact.EliminarDatosTempora();
				RequestDispatcher  rd= request.getRequestDispatcher("FacturaTempServlet");
				rd.forward(request, response);				
			} catch (DAOExcepcion e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
			
			GestionFactura factura = new GestionFactura();
			  Factura codigo1 = null;			
			  try {
				codigo1 = factura.GenerarCodigoFactura();
			} catch (DAOExcepcion e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   request.setAttribute("codigos", codigo1.getCod_factura());
			   request.getSession().setAttribute("codigos", codigo1.getCod_factura());
			
			
			RequestDispatcher  rs= request.getRequestDispatcher("menu.jsp");
			rs.forward(request, response);	
	}
}